package com.itheima.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.SysUser;
import com.itheima.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;

public class SecurityConfigUserService implements UserDetailsService {

    @Reference
    UserService userService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
           SysUser sysUser = userService.findSysUserAndRolesAndPermissionsByusername(username);
        if (sysUser == null){
            return null;
        }

        ArrayList<GrantedAuthority> list = new ArrayList<>();
        for (Role role : sysUser.getRoles()) {
            for (Permission permission : role.getPermissions()) {
                SimpleGrantedAuthority sga = new SimpleGrantedAuthority(permission.getKeyword());
                list.add(sga);
            }
        }

        UserDetails user = new User(sysUser.getUsername(),sysUser.getPassword(),list);
        return user;
    }



}
